package com.gupaoedu.design.observer.review.core;

import com.gupaoedu.design.observer.review.IMouse;
import com.gupaoedu.design.observer.review.MouseType;
import com.gupaoedu.design.observer.review.RezerMouse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * <p></p>
 *
 * @author Andy
 * @date 2018/4/23.
 */
public class EventRegister implements InvocationHandler {

    private Map<Enum, Event> eventContainer = new HashMap<>();

    private IMouse mouse;

    public void addEvent(Enum key, Object target, Method callback) {
        eventContainer.put(key, new Event(target, callback));
    }

    protected void trigger(Enum call) {
        if (!eventContainer.containsKey(call)) {
            return;
        }

        trigger(eventContainer.get(call).setTrigger(call.toString()));
    }

    private void trigger(Event event) {
        event.setSource(this);
        event.setTime(System.currentTimeMillis());
        try {
            event.getCallback().invoke(event.getTarget(), event);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public EventRegister(IMouse mouse) {
        this.mouse = mouse;
    }

    public Object getProxy() {
        Class<?> type = this.mouse.getClass();
        return Proxy.newProxyInstance(type.getClassLoader(), type.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String callBack = method.getName();
        MouseType type = MouseType.findByName(callBack);
        trigger(type);
        method.invoke(this.mouse, args);
        return null;
    }
}
